/* eslint-disable react/prop-types */
/* eslint-disable no-alert */
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Upload } from 'antd';
import React, { useState } from 'react';

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    alert('支持格式: JPG/PNG !');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    alert('文件必须小于2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const UploadAvatar = ({ title, value, onChange }) => {
  const [loading, setLoading] = useState(false);
  const handleChange = (info) => {
    setLoading(true);
    getBase64(info.file.originFileObj, (url) => {
      setLoading(false);
      onChange(url);
    });
  };
  const uploadButton = (
    <div className="uploadbtn">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        {title ?? 'Logo'}
      </div>
    </div>
  );
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {value ? (
        <img
          src={value}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};
export default UploadAvatar;
